package com.fundynamic.codekata;

public class Game {

	private int currentRoll = 0;
	private int rolls[] = new int[21];
	
	public void roll(int pins) {
		if (pins > 10) {
			throw new IllegalStateException("Mag niet!");
		}
		rolls[currentRoll] += pins;
		currentRoll++;
	}

	protected boolean isSpare(int rolls[], int index) {
		return rolls[index] + rolls[(index+1)] == 10;
		
	}
	
	public int score() {
		int score = 0;
		int frameIndex = 0;
		
		for (int frame = 0; frame < 10; frame++) {
			int currentRoll = rolls[frameIndex];
			int nextRoll = rolls[(frameIndex+1)];
			int thirdRoll = rolls[(frameIndex+2)];
			
			int scoreForFrame = 0;
			if (isStrike(rolls, frameIndex)) {
				scoreForFrame = 10 + (nextRoll + thirdRoll);
				frameIndex++;
			} else if (isSpare(rolls, frameIndex)) {
				scoreForFrame = 10 + thirdRoll;
				frameIndex += 2;
			} else {
				if (frame == 9) {
					scoreForFrame = currentRoll + nextRoll + thirdRoll;
				} else {
					scoreForFrame = currentRoll + nextRoll;
				}
				frameIndex += 2;
			}
			
			score += scoreForFrame;
		}
		return score;
	}

	private boolean isStrike(int[] rolls, int frameIndex) {
		return rolls[frameIndex] == 10;
	}

}
